//
//  SASendRecordVC.m
//  saasRetail
//
//  Created by mac on 2023/6/4.
//

#import "SASendRecordVC.h"
#import "SASendRecordCell.h"
#import "HDDatePickerView.h"
#import "SASmsSendRecordAPI.h"
#import "SASmsSendRecordModel.h"

@interface SASendRecordVC ()<UITableViewDelegate, UITableViewDataSource, HTTPAPIDelegate>

@property (nonatomic, strong) UIView *topContentView;
@property (nonatomic, strong) UILabel *startLab;
@property (nonatomic, strong) UILabel *startDateLab;
@property (nonatomic, strong) UILabel *endLab;
@property (nonatomic, strong) UILabel *endDateLab;
@property (nonatomic, strong) UIImageView *iconImageV;
@property (nonatomic, strong) UIButton *startDateBtn;
@property (nonatomic, strong) UIButton *endDateBtn;
@property (nonatomic, strong) UILabel *recordLab;
@property (nonatomic, strong) UITableView *tableView;
@property (nonatomic, assign) NSInteger currentPage;
@property (nonatomic, strong) SASmsSendRecordAPI *smsSendRecordAPI;
@property (nonatomic, strong) NSDateFormatter *dateFormatter;
@property (nonatomic, strong) NSMutableArray<SASmsSendRecordModel *> *dataMarr;


@end

@implementation SASendRecordVC

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
}

#pragma mark - HTTPAPIDelegate
- (void)fetchData:(id)data fromServerSuccessedWithAPI:(HTTPAPI *)api {
    [self.tableView.mj_header endRefreshing];
    [self.tableView.mj_footer endRefreshing];
    if (self.smsSendRecordAPI == api) {
        if (self.currentPage == 1) {
            [self.dataMarr removeAllObjects];
        }
        for (NSDictionary *dict in (NSArray *)data[@"data"][@"records"]) {
            SASmsSendRecordModel *model = [SASmsSendRecordModel mj_objectWithKeyValues:dict];
            [self.dataMarr addObject:model];
        }
    }
    [self.tableView reloadData];
}

- (void)fetchDataFromServerFailedWithError:(NSError *)error API:(HTTPAPI *)api {
    [self.tableView.mj_header endRefreshing];
    [self.tableView.mj_footer endRefreshing];
}

#pragma mark - UITableView Delegate & DataSource
-(NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    return self.dataMarr.count;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return 1;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    SASendRecordCell *cell = [tableView dequeueReusableCellWithIdentifier:@"SASendRecordCell" forIndexPath:indexPath];
    cell.model = self.dataMarr[indexPath.section];
    return cell;
}

-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
 
}

-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    return kScaleNum(126);
}

- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section {
    return [[UIView alloc] initWithFrame:CGRectZero];
}

- (UIView *)tableView:(UITableView *)tableView viewForFooterInSection:(NSInteger)section {
    return [[UIView alloc] initWithFrame:CGRectZero];
}

-(CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section {
    return kScaleNum(0.01);
}

-(CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section {
    return 10;
}

#pragma mark - event
- (void)clickStartDateBtn:(UIButton *)btn {
    WeakSelf
    HDDatePickerView *pickerView = [[HDDatePickerView alloc] initWithSlectedDate:self.startDateLab.text];
    [pickerView show];
    pickerView.selectDateBlock = ^(NSString *selectedDate) {
        NSDate *date1 = [self.dateFormatter dateFromString:selectedDate];
        NSDate *date2 = [self.dateFormatter dateFromString:weakSelf.endDateLab.text];
        if ([date1 compare:date2] == NSOrderedDescending) {
            [Prompt popPromptViewWithMsg:@"开始日期不能大于截止日期" duration:2];
        }else {
            weakSelf.startDateLab.text = selectedDate;
            weakSelf.currentPage = 1;
            weakSelf.smsSendRecordAPI.startTime = selectedDate;
            [weakSelf loadData];
        }
    };
}

- (void)clickEndDateBtn:(UIButton *)btn {
    WeakSelf
    HDDatePickerView *pickerView = [[HDDatePickerView alloc] initWithSlectedDate:self.endDateLab.text];
    [pickerView show];
    pickerView.selectDateBlock = ^(NSString *selectedDate) {
        NSDate *date1 = [self.dateFormatter dateFromString:selectedDate];
        NSDate *date2 = [self.dateFormatter dateFromString:weakSelf.startDateLab.text];
        if ([date1 compare:date2] == NSOrderedAscending) {
            [Prompt popPromptViewWithMsg:@"截止日期不能小于开始日期" duration:2];
        }else {
            weakSelf.endDateLab.text = selectedDate;
            weakSelf.currentPage = 1;
            weakSelf.smsSendRecordAPI.endTime = selectedDate;
            [weakSelf loadData];
        }
    };
}

-(void)loadData {
    
    [self.smsSendRecordAPI sendRequestToServerWithActivityViewAndMask:GET];
}

#pragma mark - initUI
-(void)initUI {
    
    [self setNavigationItemBackBBIAndTitle:@"发送记录"];
    [self setBgImage:nil];
    self.view.backgroundColor = kBgColor;

    [self.view addSubview:self.topContentView];
    [self.topContentView addSubview:self.startLab];
    [self.topContentView addSubview:self.startDateLab];
    [self.topContentView addSubview:self.endLab];
    [self.topContentView addSubview:self.endDateLab];
    [self.topContentView addSubview:self.iconImageV];
    [self.topContentView addSubview:self.startDateBtn];
    [self.topContentView addSubview:self.endDateBtn];
    
    [self.topContentView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.mas_equalTo(kScaleNum(StatusHeight));
        make.height.mas_equalTo(kScaleNum(44));
        make.right.mas_equalTo(0);
        make.left.mas_equalTo(kScaleNum(0));
    }];
    
    [self.iconImageV mas_makeConstraints:^(MASConstraintMaker *make) {
        make.center.mas_equalTo(0);
        make.size.mas_equalTo(CGSizeMake(29, 29));
    }];
    
    [self.startLab mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.equalTo(self.startDateLab);
        make.top.mas_equalTo(kScaleNum(2));
        make.height.mas_equalTo(kScaleNum(20));
    }];
    
    [self.startDateLab mas_makeConstraints:^(MASConstraintMaker *make) {
        make.right.equalTo(self.iconImageV.mas_left).offset(kScaleNum(-68));
        make.top.mas_equalTo(kScaleNum(22));
        make.height.mas_equalTo(kScaleNum(20));
    }];
    
    [self.endLab mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.equalTo(self.endDateLab);
        make.top.mas_equalTo(kScaleNum(2));
        make.height.mas_equalTo(kScaleNum(20));
    }];
    
    [self.endDateLab mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.equalTo(self.iconImageV.mas_right).offset(kScaleNum(68));
        make.top.mas_equalTo(kScaleNum(22));
        make.height.mas_equalTo(kScaleNum(20));
    }];
    
    [self.startDateBtn mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.right.equalTo(self.startDateLab);
        make.top.bottom.mas_equalTo(0);
    }];
    
    [self.endDateBtn mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.right.equalTo(self.endDateLab);
        make.top.bottom.mas_equalTo(0);
    }];
    
    NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
    [dateFormatter setDateFormat:@"yyyy-MM-dd"];
    NSString *timeFormatStr = [dateFormatter stringFromDate:[NSDate date]];
    _startDateLab.text = timeFormatStr;
    _endDateLab.text = timeFormatStr;
    
    [self.view addSubview:self.recordLab];
    [self.view addSubview:self.tableView];
    
    self.smsSendRecordAPI.pageSize = 20;
    self.smsSendRecordAPI.startTime = timeFormatStr;
    self.smsSendRecordAPI.endTime = timeFormatStr;
    self.currentPage = 1;
    [self loadData];
    
    __weak typeof(self) weakSelf = self;
    self.tableView.mj_header = [MJRefreshNormalHeader headerWithRefreshingBlock:^{
        [weakSelf.view endEditing:YES];
        weakSelf.currentPage = 1;
        [weakSelf loadData];
    }];
    MJRefreshAutoStateFooter *mj_footer = [MJRefreshAutoStateFooter footerWithRefreshingBlock:^{
        [weakSelf.view endEditing:YES];
        weakSelf.currentPage ++;
        [weakSelf loadData];
    }];
    [mj_footer setTitle:@"已经到底啦~" forState:MJRefreshStateIdle];//设置闲置状态下不显示“点击或上拉加载更多”
    self.tableView.mj_footer = mj_footer;
}

#pragma mark - lazy
- (UIView *)topContentView {
    if (!_topContentView) {
        _topContentView = [[UIView alloc] init];
        _topContentView.backgroundColor = [UIColor whiteColor];
    }
    return _topContentView;
}

- (UILabel *)startLab {
    if (!_startLab) {
        _startLab = [[UILabel alloc] init];
        _startLab.textColor = kBlackColor;
        _startLab.font = kFont(15);
        _startLab.text = @"开始";
    }
    return _startLab;
}

- (UILabel *)startDateLab {
    if (!_startDateLab) {
        _startDateLab = [[UILabel alloc] init];
        _startDateLab.textColor = kBlackColor;
        _startDateLab.font = kFont(15);
    }
    return _startDateLab;
}

- (UILabel *)endLab {
    if (!_endLab) {
        _endLab = [[UILabel alloc] init];
        _endLab.textColor = kBlackColor;
        _endLab.font = kFont(15);
        _endLab.text = @"截止";
    }
    return _endLab;
}

- (UILabel *)endDateLab {
    if (!_endDateLab) {
        _endDateLab = [[UILabel alloc] init];
        _endDateLab.textColor = kBlackColor;
        _endDateLab.font = kFont(15);
    }
    return _endDateLab;
}

- (UIImageView *)iconImageV {
    if (!_iconImageV) {
        _iconImageV = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"SA_to"]];
    }
    return _iconImageV;
}

- (UIButton *)startDateBtn {
    if (!_startDateBtn) {
        _startDateBtn = [UIButton buttonWithType:UIButtonTypeCustom];
        [_startDateBtn addTarget:self action:@selector(clickStartDateBtn:) forControlEvents:UIControlEventTouchUpInside];
    }
    return _startDateBtn;
}

- (UIButton *)endDateBtn {
    if (!_endDateBtn) {
        _endDateBtn = [UIButton buttonWithType:UIButtonTypeCustom];
        [_endDateBtn addTarget:self action:@selector(clickEndDateBtn:) forControlEvents:UIControlEventTouchUpInside];
    }
    return _endDateBtn;
}

-(UILabel *)recordLab {
    if (!_recordLab) {
        _recordLab = [[UILabel alloc] initWithFrame:SARectMake(10, StatusHeight + 65, 200, 15)];
        _recordLab.font = kFont(15);
        _recordLab.textColor = kBlackColor;
        _recordLab.text = @"查询记录";
    }
    return _recordLab;
}

-(UITableView *)tableView {
    if (!_tableView) {
        _tableView = [[UITableView alloc] initWithFrame:CGRectMake(0, kScaleNum(StatusHeight + 90), kScreenWidth, kScreenHeight - kScaleNum(StatusHeight + 90)) style:UITableViewStyleGrouped];
        _tableView.backgroundColor = kBgColor;
        _tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
        _tableView.delegate = self;
        _tableView.dataSource = self;
        _tableView.showsHorizontalScrollIndicator = NO;
        _tableView.contentInsetAdjustmentBehavior = UIScrollViewContentInsetAdjustmentNever;
        _tableView.estimatedRowHeight = 0;
        _tableView.estimatedSectionHeaderHeight = 0;
        _tableView.estimatedSectionFooterHeight = 0;
        [_tableView registerClass:[SASendRecordCell class] forCellReuseIdentifier:@"SASendRecordCell"];
    }
    return _tableView;
}

-(SASmsSendRecordAPI *)smsSendRecordAPI {
    if (!_smsSendRecordAPI) {
        _smsSendRecordAPI = [SASmsSendRecordAPI apiWithDelegate:self];
    }
    return _smsSendRecordAPI;
}

-(NSDateFormatter *)dateFormatter {
    if (!_dateFormatter) {
        _dateFormatter = [NSDateFormatter new];
        [_dateFormatter setDateFormat:@"yyyy-MM-dd"];
    }
    return _dateFormatter;
}

-(NSMutableArray<SASmsSendRecordModel *> *)dataMarr {
    if (!_dataMarr) {
        _dataMarr = [NSMutableArray array];
    }
    return _dataMarr;
}

@end
